package lero.interceptor;

import lero.pojo.Admin;
import lero.service.AuthorServiceI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 作者: lero
 * 日期：2018/7/23
 */

public class AuthorInerceptor extends HandlerInterceptorAdapter {

    @Autowired
    AuthorServiceI  authorServiceI;

    private static final Logger logger = LoggerFactory.getLogger(AuthorInerceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        logger.info("请求URI为:"+uri);
        //登录退出登录请求不拦截
        if(uri.contains("login")||uri.contains("logout")){
            return  true;
        }

        Admin admin =(Admin) request.getSession().getAttribute("loginUser");
        //如果是超级管理员，具有所有权限
        if(admin.getLevel().equals("9")){
            return  true;
        }

        String type = request.getHeader("X-Requested-With");// XMLHttpRequest

        //缓存权限
        List<Map<String, Object>> authors =(List<Map<String, Object>>) request.getSession().getAttribute("ownAuthor");
        if(authors ==null){
            authors = authorServiceI.selectCurrentAdminOwnAuthor(admin);
            request.getSession().setAttribute("ownAuthor",authors);
        }
        logger.info("当前用户【{}】，拥有的权限为【{}】:",admin.getUsername(),authors);
        Boolean  flag =false;
        if(authors!=null &&authors.size()>0){
            out: for (Map  temp :authors) {
                String url =(String) temp.get("href");
                url=url.trim();
                if(url!=null &&! url.trim().equals("") ){
                    String[] arr = url.split(",");
                    for(int i=0;i<arr.length;i++){
                        if(uri.contains(arr[i])){
                            flag=true;
                            break out;
                        }
                    }
                }
            }
        }
        if(flag){
           return true;
        }else{
            if ("XMLHttpRequest".equals(type)) {
                // ajax请求
                response.setHeader("SESSIONSTATUS", "TIMEOUT");
                response.setHeader("CONTEXTPATH", "/layuicms/page/404.html");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);//403 禁止
            } else {
                response.sendRedirect("/layuicms/page/404.html");
            }
            return  false;
        }
       // return  true;
    }
}
